package com.mt.mtbusinessmanagementsystem.interceptor;

import com.mt.mtbusinessmanagementsystem.constant.JWTConstant;
import com.mt.mtbusinessmanagementsystem.pojo.properties.JWTProperties;
import com.mt.mtbusinessmanagementsystem.utils.CurrentUserHolder;
import com.mt.mtbusinessmanagementsystem.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

@Component
@Slf4j
public class JwtTokenInterceptor implements HandlerInterceptor {

    @Autowired
    private JWTProperties jwtProperties;
    //此方法会在方法执行前执行
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        System.out.println("当前线程的id：" + Thread.currentThread().getId());
        //判断当前拦截到的是Controller的方法还是其他资源
        if (!(handler instanceof HandlerMethod)) {
            //当前拦截到的不是动态方法，直接放行
            return true;
        }

        //1、从请求头中获取令牌
        String token = request.getHeader(jwtProperties.getTokenName());
        //2、校验令牌
        try {
            log.info("jwt校验:{}", token);
            //解析并获取JWT令牌第二部分内容
            Claims claims = JwtUtils.parseJWT(jwtProperties.getSecretKey(), token);
            Map map =(HashMap<String,Object>) claims.get(JWTConstant.CLAIMS);
            System.out.println(map.get(JWTConstant.EMPLOYEE_ID));
            //获取JWT令牌第二部分的id值
            String employee = map.get(JWTConstant.EMPLOYEE_ID).toString();
            String account = map.get(JWTConstant.ACCOUNT).toString();
            String password = map.get(JWTConstant.PASSWORD).toString();
            log.info("当前员工的信息：{} {} {}", employee,account,password);
            CurrentUserHolder.setClaims(claims);
            //3、通过，放行
            return true;
        } catch (Exception ex) {
            //4、不通过，响应401状态码
            response.setStatus(401);
            return false;
        }
    }
}